package com.soulkun.smarthome.logic.interceptor;

import com.soulkun.smarthome.logic.domain.AntiReplayHeaders
import com.soulkun.smarthome.logic.utils.SignatureUtils
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

class AntiReplayInterceptor: Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        return chain.proceed(chain.request().setAntiReplay())
    }

    private fun Request.setAntiReplay(): Request {
        val antiReplay = this.header("Anti-Replay") //如果没有，默认为false
        return if (antiReplay == "true") {
            val antiReplayHeaders =
                AntiReplayHeaders(System.currentTimeMillis().toString(), SignatureUtils.generateNonce())
            this.newBuilder()
                .addHeader(AntiReplayHeaders.HEADER_TIMESTAMP, antiReplayHeaders.timestamp)
                .addHeader(AntiReplayHeaders.HEADER_NONCE, antiReplayHeaders.nonce)
                .build()
        }else{
            this
        }
    }

}
